/*
 * Copyright (c) 2005-2007 feyaSoft Corp. All Rights Reserved.
 */
package com.feyaSoft.plugin.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

/**
 * This class is used to
 * 
 * @author fzhuang
 * @date Feb 20, 2006
 */
public class Convertor {

	static final long ONE_HOUR = 60 * 60 * 1000L;

	/**
	 * Convert string to int
	 * 
	 * @param in
	 * @return
	 */
	public static int string2Int(String in) {
		return Integer.parseInt(in);
	}

	/**
	 * Convert string to double
	 * 
	 * @param in
	 * @return
	 */
	public static double string2Double(String in) {
		return Double.parseDouble(in);
	}

	/**
	 * Convert int to String
	 * 
	 * @param in
	 * @return
	 */
	public static String int2String(int in) {
		return Integer.toString(in);
	}

	/**
	 * Convert double to String
	 * 
	 * @param in
	 * @return
	 */
	public static String double2String(double in) {
		return Double.toString(in);
	}

	/**
	 * Convert general string stuff to html format.
	 * 
	 * @param message
	 *            Text Source
	 * @return Modified Text
	 */
	public static String convert2HTML(String message) {

		// check whether it is empty string
		if (message == null || message.length() == 0) {
			return "";
		}

		StringBuffer buffer = new StringBuffer();
		String[] separator = message.split("(\r?\n)|(\n[^\r])");

		for (int i = 0; i < separator.length; i++) {
			buffer.append(separator[i]);
			if (i < (separator.length - 1)) {
				buffer.append("<br/>");
			}
		}
		return (buffer.toString());
	}

	public static List splitToList(String s, String devider) {
		List result = new ArrayList();
		StringTokenizer stTmp = new StringTokenizer(s, devider, false);

		while (stTmp.hasMoreTokens()) {
			String part = (String) stTmp.nextElement();
			result.add(part);
		}

		return result;
	}

	/**
	 * convert list to string which separate by separator
	 * 
	 * @param ids
	 * @return
	 */
	public static String listToString(List<Long> ids, String separator) {
		StringBuffer result = new StringBuffer();
		int total = ids.size();

		if (ids == null || ids.size() == 0) {
			return null;
		}

		for (int i = 0; i < total; i++) {
			Long id = ids.get(i);
			result.append(id.toString());

			// check whether it is last one
			if ((i + 1) < total) {
				result.append(separator);
			}
		}

		return result.toString();
	}

	public static long daysBetween(Date d1, Date d2) {
		return ((d2.getTime() - d1.getTime() + ONE_HOUR) / (ONE_HOUR * 24));
	}
}
